package svc

import (
	"database/sql"

	"mall/common/modelx"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/repository"
	"mall/service/forum/rpc/internal/config"
	"mall/service/user/rpc/userclient"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config config.Config

	ForumPost     repository.ForumPostRepository
	ForumTopic    repository.ForumTopicRepository
	ForumReaction repository.ForumReactionRepository
	ForumUser     repository.ForumUserRepository

	DB                  *sql.DB
	Post                repository.PostRepository
	Topic               repository.TopicRepository
	Reaction            repository.ReactionRepository
	User                repository.UserRepository
	ForumTerm           repository.ForumTermRepository
	ForumComment        repository.CommentRepository
	UserCollect         repository.UserCollectRepository
	ForumPerfumeCabinet repository.PerfumeCabinetRepository

	EsClient *elasticsearch.Client

	BlogRpc blogclient.Blog
	UserRpc userclient.User
}

func NewServiceContext(c config.Config) *ServiceContext {
	db, err := modelx.NewMysqlConn(c.Mysql.DataSource)
	if err != nil {
		logx.Must(err)
	}

	esClient, err := newElasticClient(c)
	if err != nil {
		logx.Must(err)
	}

	return &ServiceContext{
		Config: c,

		ForumPost:     repository.NewForumPostRepository(c.Mysql.DataSource, c.CacheRedis),
		ForumTopic:    repository.NewForumTopicRepository(c.Mysql.DataSource, c.CacheRedis),
		ForumReaction: repository.NewForumReactionRepository(c.Mysql.DataSource, c.CacheRedis),
		ForumUser:     repository.NewForumUserRepository(c.Mysql.DataSource, c.CacheRedis),

		DB:                  db,
		Post:                repository.NewPostRepository(db, c.CacheRedis),
		Topic:               repository.NewTopicRepository(db, c.CacheRedis),
		Reaction:            repository.NewReactionRepository(db, c.CacheRedis),
		User:                repository.NewUserRepository(db, c.CacheRedis),
		ForumTerm:           repository.NewForumTermRepository(db, c.CacheRedis),
		ForumComment:        repository.NewCommentRepository(db, c.CacheRedis),
		UserCollect:         repository.NewUserCollectRepository(db),
		ForumPerfumeCabinet: repository.NewPerfumeCabinetRepository(db, c.CacheRedis),

		EsClient: esClient,

		BlogRpc: blogclient.NewBlog(zrpc.MustNewClient(c.BlogRpc)),
		UserRpc: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
	}
}
